mod hello;
mod error500;
mod handle404;

use salvo::cors::Cors;
use salvo::http::Method;
use salvo::catcher::Catcher;
use salvo::prelude::*;


use hello::{ hello_world, hello_json };
use error500::error500_handler;
use handle404::handle404_handler;


pub async fn create_service() -> Service {

    println!("current_dir: {:?}", std::env::current_dir().unwrap());

    let base_dir = std::env::current_dir()
        .unwrap()
        .join("./static")
        .canonicalize()
        .unwrap();

    println!("static Base Dir: {base_dir:?}");

    let session_handler = salvo::session::SessionHandler::builder(
        salvo::session::MemoryStore::new(),
        b"secretabsecretabsecretabsecretabsecretabsecretabsecretabsecretab",
    )
        .build()
        .unwrap();

    let cors = Cors::new()
        .allow_origin(["http://127.0.0.1:5800", "http://localhost:5800"])
        .allow_methods(vec![Method::GET, Method::POST, Method::DELETE])
        .allow_headers("authorization")
        .into_handler();

    let router =Router::new()
        .hoop(session_handler)
        .push(
            Router::with_path("500").get(error500_handler)
        )
        .push(
            Router::with_path("hello").get(hello_world)
        )
        .push(
            Router::with_path("hello_json").get(hello_json)
        );
        Router::default().push(
            Router::with_hoop(Compression::new().force_priority(true))
                .path("ws_chat")
                .get(StaticFile::new(base_dir.join("ws_chat.txt"))),
        )
        .push(
            Router::with_hoop(Compression::new().enable_brotli(CompressionLevel::Fastest))
                .path("sse_chat")
                .get(StaticFile::new(base_dir.join("sse_chat.txt"))),
        )
        .push(
            Router::with_hoop(Compression::new().enable_zstd(CompressionLevel::Fastest))
                .path("todos")
                .get(StaticFile::new(base_dir.join("todos.txt"))),
        )
        .push(
            Router::with_hoop(Compression::new().enable_gzip(CompressionLevel::Fastest))
                .path("<*path>")
                .get(StaticDir::new(base_dir)),
        );

    let doc = OpenApi::new("test api", "0.0.1").merge_router(&router);

    let router = router
        .unshift(doc.into_router("/api-doc/openapi.json"))
        .unshift(SwaggerUi::new("/api-doc/openapi.json").into_router("/swagger-ui"));

        Service::new(router)
            .hoop(Logger::new())
            .hoop(cors)
            .catcher(Catcher::default().hoop(handle404_handler))
    // let router = router
    //     .unshift(doc.into_router("/api-doc/openapi.json"))
    //     .unshift(SwaggerUi::new("/api-doc/openapi.json").into_router("swagger-ui")
}